<template>
  <a-card :bordered="false">
     <!-- 一审 -->
    <!-- 操作按钮区域 -->
    <div class="table-operator"  v-if="!formDisabled">
      <a-button  @click="handleAdd" type="primary" icon="plus" :disabled="dataSource.length !== 0 || revokedType">新增</a-button>
    </div>

    <!-- table区域-begin -->
    <div>
      <a-table
        ref="table"
        size="middle"
        :scroll="{x:true}"
        bordered
        rowKey="key"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="false"
        :loading="loading"
        class="j-table-force-nowrap"
        @change="handleTableChange">
        <!-- 关联项目 -->
        <span slot="projectId" slot-scope="text, record">
          <select-project-input v-if="!disabled" :disabled="disabled" v-model="record.projectId" placeholder="请选择关联项目" />
          <a @click="onDetail(text)" v-else :title="filterMultiDictText(dictOptions['projectId'], text + '')">{{ filterMultiDictText(dictOptions['projectId'], text + '') }}</a>
        </span>

        <!-- 领用数量标题定制 -->
        <span slot="amountTitle"><span style="color: red; text-align: center;">*</span> 数量</span>
        <span slot="budgetAmountTitle"><span style="color: red; text-align: center;">*</span> 预算单价(元)</span>
        <!-- 预计审核费 -->
        <span slot="expectedAuditFee" slot-scope="text, record">
          <a-input-number
            :max="99999999"
            :min="0"
            :disabled="twoProjectSpecialist"
            :precision="2"
            v-model="record.expectedAuditFee"
            placeholder="请输入"
            @blur="calculateActualFee(record)"
            style="width: 100%" />
        </span>
        <!-- 扣除比例 -->
        <div slot="deductionRatio" slot-scope="text, record">
          <div><j-dict-select-tag :triggerChange="false" :disabled="twoProjectSpecialist"  @blur="calculateActualFee(record)" placeholder="请选择扣除比例" v-model="record.deductionRatio"  dictCode="deduction_ratio"/></div>
        </div>
        <!-- 实际审核费 -->
        <span slot="actualAuditFee" slot-scope="text, record">
          <a-input-number
            disabled
            :max="99999999"
            :min="0"
            :precision="2"
            v-model="record.actualAuditFee"
            placeholder="请输入"
            style="width: 100%"
          />
          <!-- <span v-else>{{ record.contractRate }}</span> -->
        </span>
        <!-- <span slot="allAmount" slot-scope="text, record">
          {{ record.amount * record.budgetAmount }}
        </span> -->

        <span v-if="!revokedType && !formDisabled" slot="action" slot-scope="text, record">
          <!-- <a-button
                    class="ruleButton"
                    :ghost="true"
                    type="primary"
                    icon="edit"
                    @click="handleEdit(record)"
                    :disabled="isDisabledAuth('erpReportAudit:edit')"
            /> -->
          <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.key)">
            <a-button
              class="ruleButton"
              icon="delete"
              :disabled="isDisabledAuth('erpPurchaseApplyFormDetail:delete')"/>
          </a-popconfirm>
        </span>

      </a-table>
    </div>

    <!-- <a-col :span="24" >
                <h4 style="margin-top: 15px;">一审结果文件:</h4>
            <a-form-model-item label="任务附件" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="attachment">
              <j-upload v-if="!disabled" :disabled="disabled" v-model="model.attachment"></j-upload>
              <a-button v-else icon="download" :disabled="isRequesting" @click="viewFile(model.attachment)">文件列表</a-button>
            </a-form-model-item>
            <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remark">
              <a-textarea
              :disabled="twoProjectSpecialist" 
                :max-length="200"
                v-model="model.remark"
                rows="4"
                placeholder="请输入备注" />
            </a-form-model-item>
              </a-col> -->

    <ErpFirstInstanceEngineerModal ref="modalForm" @dataOne="dataOne" @ok="modalFormOk"></ErpFirstInstanceEngineerModal>
    <view-file-modal ref="viewFileModal"></view-file-modal>
    <!-- 项目详情开始 -->
    <erp-project-report-modal ref="projectForm"></erp-project-report-modal>
    <!-- 项目详情结束 -->
  </a-card>
</template>

<script>

import '@/assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import ErpFirstInstanceEngineerModal from './ErpFirstInstanceEngineerModal'
import { DisabledAuthFilterMixin } from '@/mixins/DisabledAuthFilterMixin'
import AuditModal from '@/views/scy/components/AuditModal'
import { filterObj } from '@/utils/util'
import { getAction } from '@/api/manage'
// import { viewFile } from '@/utils/util'
import ViewFileModal from '@/views/scy/components/ViewFileModal'

import Vue from 'vue'
import { filterMultiDictText, initDictOptions } from '@/components/dict/JDictSelectUtil'
import ErpProjectReportModal from '@/views/erp/report/project/modules/ErpProjectReportModal'
import SelectProjectInput from '@/views/scy/components/SelectProjectInput'

  export default {
    name: 'ErpFirstInstanceEngineerList',
    mixins: [mixinDevice, DisabledAuthFilterMixin],
    components: {
      ErpProjectReportModal,
      ErpFirstInstanceEngineerModal,
      AuditModal,
      ViewFileModal,
      SelectProjectInput
    },
    props: {
      // 表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      },

      twoProjectSpecialist:{
        type: Boolean,
        default: false,
        required: false
      },
      formDisabled:{
        type: Boolean,
        default: false,
        required: false
      },
      revokedType:{
        type: Boolean,
        default: false,
        required: false
      },
      formBpm:{
        type: Boolean,
        default: false,
        required: false
      },
      deleteAbled:{
        type: String,
        default: '0',
        required: false
      },
      applys:{
        type: String,
        default: '',
        required: false
      }
    },
    data () {
      return {
        filterMultiDictText,
        isRequesting: false,
        params: {
          billId: null
        },
        /* 查询条件-请不要在queryParam中声明非字符串值的属性 */
        queryParam: {},
        /* 数据源 */
        dataSource: [
 
        ],
        // formDisabled:false,
        labelCol: {},
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 24 }
      },
        model:{
          attachment:'',
          remark:'',
          userType:'one_engineer'
        },
        /* 分页参数 */
        ipagination: {
          current: 1,
          pageSize: 10,
          pageSizeOptions: ['10', '20', '30', '50', '100', '200'],
          showTotal: (total, range) => {
            return range[0] + '-' + range[1] + ' 共' + total + '条'
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0
        },
        /* 排序参数 */
        isorter: {
          column: 'createTime',
          order: 'desc'
        },
        /* 筛选参数 */
        filters: {},
        /* table加载状态 */
        loading: false,
        /* table选中keys */
        selectedRowKeys: [],
        /* table选中records */
        selectionRows: [],
        /* 查询折叠 */
        toggleSearchStatus: false,
        /* 高级查询条件生效状态 */
        superQueryFlag: false,
        /* 高级查询条件 */
        superQueryParams: '',
        /** 高级查询拼接方式 */
        superQueryMatchType: 'and',
        iconStyle: { 'font-size': '18px', 'cursor': 'pointer' },
        colsettings: ':colsettings',
        description: '采购申请单明细管理页面',
        // 表头
        // columns: [],
        // 列设置
        settingColumns: [],
        // 列定义
        columns: [
        {
          title: '姓名',
          dataIndex: 'empId',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: (text) => {
          if (!text) {
            return ''
          } else {
              return filterMultiDictText(this.dictOptions['empId'], text + '')
          }
         }
        },
        {
          title: '所属团队',
          align: 'center',
          dataIndex: 'teamId',
          width: 100,
          ellipsis: true,
          customRender: (text) => {
          if (!text) {
            return ''
          } else {
              return filterMultiDictText(this.dictOptions['teamId'], text + '')
          }
         }
        },
        {
          title: '预计审核费(元)',
          align: 'center',
          dataIndex: 'expectedAuditFee',
          scopedSlots: { customRender: 'expectedAuditFee' },
          width: 140,
          ellipsis: true
        },
        {
          title: '扣除比例(%)',
          align: 'center',
          dataIndex: 'deductionRatio',
          scopedSlots: { customRender: 'deductionRatio' },
          width: 135,
          ellipsis: true
        },
        {
          title: '实际审核费(元)',
          scopedSlots: { customRender: 'actualAuditFee' },
          align: 'center',
          dataIndex: 'actualAuditFee',
          width: 120,
          ellipsis: true
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          // fixed: 'right',
          width: 150,
          scopedSlots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'action'
          }
        }

      ],
        url: {
          list: '/api/erp/purchase/procurement/erpPurchaseApplyFormDetail/allList', // 列表
          queryByProjectId: '/api/erp/project/report/erpProjectReport/queryById' 
        },
        dictOptions: {},
        superFieldList: []
      }
    },
    created() {
      // 加载数据字典信息
      this.initDictConfig();
      this.getSuperFieldList();
      if (!this.disableMixinCreated) {
        this.initColumns()
      }
      if (!this.revokedType || this.formBpm) {
        // console.log(this.revokedType,'this.revokedType--------');
        console.log('ssssssssssss---');
        
        this.columns.pop()
      }
    },
    filters: {
      statusFilter(status) {
        const statusMap = {
          '0': '待提交',
          '1': '待审核',
          '2': '已审核'
        }
        return statusMap[status] || status
      },
      statusTypeFilter(type) {
        const statusTypeMap = {
          '0': 'success',
          '1': 'success',
          '2': 'success'
        }
        return statusTypeMap[type] || 'success'
      }
    },
    computed: {
    },
    methods: {
     async viewFile(text) {
      if (!text) {
        this.$message.warning('无可下载文件')
        return
      }
      try {
        this.isRequesting = true;
        await this.$refs.viewFileModal.show(text);
        this.isRequesting = false;
        } catch (error) {
        } finally {
          // 无论成功或失败，最后解锁按钮
          this.isRequesting = false;
        }

    },
      initDictConfig() {
        // 人员
        initDictOptions('erp_employee_file,name,id').then((res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'empId', res.result)
          }
        })
        // 团队
        initDictOptions('erp_omc_team_manager,alias_name,id').then((res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'teamId', res.result)
          }
        })
      },
      getSuperFieldList() {
        let fieldList = [];
        fieldList.push({ type: 'string', value: 'empId', text: '姓名', dictCode: '' })
        fieldList.push({ type: 'string', value: 'teamId', text: '所属团队', dictCode: '' })
        fieldList.push({ type: 'string', value: 'expectedAuditFee', text: '预计审核费(元)', dictCode: '' })
        fieldList.push({ type: 'string', value: 'deductionRatio', text: '扣除比例(%)', dictCode: '' })
        fieldList.push({ type: 'string', value: 'actualAuditFee', text: '实际审核费(元)', dictCode: '' })
        // fieldList.push({ type: 'int', value: 'amount', text: '数量', dictCode: '' })
        // fieldList.push({ type: 'string', value: 'unit', text: '单位', dictCode: '' })
        // fieldList.push({ type: 'BigDecimal', value: 'referencePrice', text: '参考价格', dictCode: '' })
        this.superFieldList = fieldList
      },
        // 计算实际审核费
       calculateActualFee(record) {
        // 确保数值类型
        const amount = Number(record.expectedAuditFee) || '0'
        const rate = Number(record.deductionRatio) || '0'
        
        // 计算实际费用（预计审核费 * (1 - 扣除比例)）
        const actual = amount * (1 - rate)
        
        // 使用$set确保响应式更新
        this.$set(record, 'actualAuditFee', parseFloat(actual.toFixed(2)))
      },
      changVal(val){
        console.log('val---', val)
      },
      getSelectedRowKeys() {
        var ids = ''
        for (var a = 0; a < this.selectedRowKeys.length; a++) {
          ids += this.selectedRowKeys[a] + ','
        }
        return ids
      },
      loadData(arg, id) {
        if (!this.url.list) {
          this.$message.error('请设置url.list属性!')
          return
        }
        // 加载数据 若传入参数1则加载第一页的内容
        if (arg === 1) {
          this.ipagination.current = 1
        }
        this.params = this.getQueryParams() // 查询条件
        if (id) {
          this.params.billId = id
        }
        this.loading = true
        getAction(this.url.list, this.params).then(res => {
          if (res.success) {
            // update-begin---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
            this.dataSource = res.result.records || res.result
            this.dataSource.forEach((item, index) => {
              item.key = index
            })
            this.onData()
            if (res.result.total) {
              this.ipagination.total = res.result.total
            } else {
              this.ipagination.total = 0
            }
            // 判断是否当前页没有数据且不为第一页
            if (this.dataSource.length == 0 && this.ipagination.current != 1) {
              this.ipagination.current = this.ipagination.current - 1
              this.loadData(this.ipagination.current - 1);
            }
            // update-end---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
          }
          if (res.code === 510) {
            this.$message.warning(res.message)
          }
          this.loading = false
        })
      },
      getQueryParams() {
        // 获取查询条件
        let sqp = {}
        if (this.superQueryParams) {
          sqp['superQueryParams'] = encodeURI(this.superQueryParams)
          sqp['superQueryMatchType'] = this.superQueryMatchType
        }
        var param = Object.assign(sqp, this.queryParam, this.isorter, this.filters)
        param.field = this.getQueryField()
        param.pageNo = this.ipagination.current
        param.pageSize = this.ipagination.pageSize
        return filterObj(param)
      },
      getQueryField() {
        // TODO 字段权限控制
        var str = 'id'
        this.columns.forEach(function (value) {
          // 多表头字段
          if (value.dataIndex == null && value.dataIndex === undefined) {
            value.children.forEach(function (item) {
              str += ',' + item.dataIndex.replace('_dictText', '')
            })
          } else {
            str += ',' + value.dataIndex
          }
        })
        return str
      },

      onSelectChange(selectedRowKeys, selectionRows) {
        this.selectedRowKeys = selectedRowKeys
        this.selectionRows = selectionRows
      },
      onClearSelected() {
        this.selectedRowKeys = []
        this.selectionRows = []
      },
      searchQuery() {
        this.loadData(1)
      },
      superQuery() {
        this.$refs.superQueryModal.show()
      },
      handleDelete: function (key) {
        if (this.dataSource.length == 1) {
          this.dataSource = []
          this.onData()
          return
        }
        this.dataSource.splice(key, 1);
        this.dataSource.forEach((item, index) => {
          item.key = index
        })
        this.onData()
      },
      handleEdit: function (record) {
        this.$refs.modalForm.edit(record)
        this.$refs.modalForm.title = '编辑'
        this.$refs.modalForm.disableSubmit = false
      },
      handleAdd: function () {
        this.$refs.modalForm.add()
        this.$refs.modalForm.title = '新增'
        this.$refs.modalForm.disableSubmit = false
      },
      handleTableChange(pagination, filters, sorter) {
        // 分页、排序、筛选变化时触发
        this.filters = {}
        if (Object.keys(filters).length > 0) {
          for (let key in filters) {
            let value = filters[key].join(',')
            if (value) {
              if (key.indexOf('_dictText') != -1) {
                key = key.substring(0, key.indexOf('_dictText'))
              }
              this.filters[key] = value
            }
          }
        }
        if (Object.keys(sorter).length > 0) {
          this.isorter.column = sorter.field
          this.isorter.order = sorter.order == 'ascend' ? 'asc' : 'desc'
        }
        this.ipagination = pagination
        this.loadData()
      },
      modalFormOk() {
        // 新增/修改 成功时，重载列表
        this.loadData()
        // 清空列表选中
        this.onClearSelected()
      },
      initColumns() {
        // 权限过滤（列权限控制时打开，修改第二个参数为授权码前缀）
        // this.defColumns = colAuthFilter(this.defColumns,'testdemo:');
        if (this.defColumns) {
          var key = this.$route.name + this.colsettings
          let colSettings = Vue.ls.get(key)
          if (colSettings == null || colSettings == undefined) {
            let allSettingColumns = []
            this.defColumns.forEach(function (item, i, array) {
              allSettingColumns.push(item.dataIndex)
            })
            this.settingColumns = allSettingColumns
            this.columns = this.defColumns
          } else {
            Vue.ls.set(key, colSettings, 7 * 24 * 60 * 60 * 1000)
            this.settingColumns = colSettings
            const cols = this.defColumns.filter(item => {
              if (item.key == 'rowIndex' || item.dataIndex == 'action') {
                return true
              }
              if (colSettings.includes(item.dataIndex)) {
                return true
              }
              return false
            })
            this.columns = cols
          }
        }
      },
      dataOne(data, flag) {
        console.log('data---', data)
        console.log('flag---', flag)
        if (flag) {
          // this.dataSource.push(data)
          // this.dataSource.forEach((item, index) => {
          //   item.key = index
          // })

          // this.dataSource.push(data)
          this.dataSource.push({
              ...data,
              expectedAuditFee:'0',
              deductionRatio:'0',
              actualAuditFee:'0'
            })
          this.dataSource.forEach((item, index) => {
            item.key = index
          })
        } else {
          this.dataSource.splice(data.key, 1, data);
        }
      },
      onBlur (record, index) {
       console.log('record',record);
       console.log('index',index);
       
        // this.$set(this.dataSource[record.key], 'allAmount', (record.amount * record.budgetAmount).toFixed(2))
        this.onData()
      },
      onData() {
        this.$emit('applyDetailData', this.dataSource);
      },
      submitForm() {
        return this.dataSource
      },
      onDetail(id) {
        console.log('-------id', id)
        const that = this
        this.$nextTick(() => {
          getAction(this.url.queryByProjectId, { id: id }).then((res) => {
            if (res.success) {
              const model = res.result
              that.$refs.projectForm.getDetail(model);
              that.$refs.projectForm.title = '项目一览表';
            }
          })
        })
      }
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less';
</style>
